package com.jy.api.domain;

import com.aliyun.opensearch.sdk.dependencies.org.json.JSONArray;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * Created by hanxi on 2017/7/8.
 * 商品表
 */
@Slf4j
@Entity
@Data
@NoArgsConstructor
@NamedEntityGraph(name = "Product.productType", attributeNodes = @NamedAttributeNode("productType"))
public class Product {
    @Id
    @Column(length = 50)
    private String id;
    private String storeId;
    private String name;
    private String pinyin;
    private String barCode;
    @ManyToOne
    private ProductType productType;
    private double costPrice = 0;
    private double salesPrice;
    private String supplierName;
    private ProductStatus productStatus = ProductStatus.ON;
    private String imageURL;
    @Column(insertable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date addTime;
    private Date updateTime;
    private boolean enabled = true;
    private int quantity = 0;
    private String typeName;
    private String parentTypeName;
    private int productQty = 1;
    //设置商品阈值数量
    private int threshold = 0;

    private boolean salesEnabled = false;

    private boolean salesShowEnabled = false;

    private int salesCount = 0;

    private int sort;

    private String note;
    /**
     * 零售单位与库存单位的比率。比如一条烟等于10包，该值为10
     *
     * @deprecated 即将转移到Inventory
     */
    private int stockQuantityRatio = 1;
    /**
     * 库存单位价格
     *
     * @deprecated 即将转移到Inventory
     */

    private int stockPrice = 0;

    @Temporal(TemporalType.TIMESTAMP)
    private Date lastCheckTime;
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastStockInTime;
    /**
     * 是否管理库存
     */
    private boolean stockEnabled = true;
    /**
     * 是否允许会员赠送金额支付
     */
    private boolean allowMemberBonusPay = false;

    /**
     * 固定提成金额
     */
    private double commission = 0;

    /**
     * 是否管理原材料
     */
    @Column(name = "is_material_enabled")
    private boolean materialEnabled = false;
    /**
     * 是否制作商品
     */
    private boolean makeEnabled=false;

    private boolean schedulingEnabled=false;

    /**
     * 是否支持厨房打印
     */
    private boolean kitchenPrintEnabled = false;


    private String supplyTimes;

    //是否是配品
    private boolean matchProductEnabled;
    //是否含有配品
    private boolean haveMatchProductEnabled;
    //是否开启配品点单
    private  boolean openMatchEnabled;


    @Type(type = "com.jy.api.domain.json.StringArrayJson")
    @Column(columnDefinition = "text")
    private List<String> productId = new ArrayList<>();


    /*
     *
     * 是否进行热敏打印
     */
    private boolean isDirectThermal = false;

    private double memberPrice;

    private boolean memberShow;

    private double disPrice;

    private boolean disShow;

    private String week;

    private String nowHours;

    private String tomorrowHour;

    private boolean cross;

    private double disCom;

    private boolean showEnabled = true;

    private boolean purchaseEnabled = true;

    private boolean labelEnabled = false;

    private int ipId = 0;

    private String ipName = "";
    @Type(type = "com.jy.api.domain.json.StringArrayJson")
    @Column(columnDefinition = "text")
    private List<String> tips;


    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "product_id")
    @Where(clause = "`enabled`=1")
    protected List<ProductMaterialItem> productMaterialItems;//关联商品原料

    private int port = 0;

    private String ipAddress = "";

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy(value = "addTime")
    @JoinColumn(name = "product_id")
    public List<EmployeeCommission> commissions;

    public boolean openTimeEnabled = false;

    private boolean postEnabled;
    @Type(type = "com.jy.api.domain.json.StringArrayJson")
    @Column(columnDefinition = "text")
    private List<String> specs=new ArrayList<>();

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy(value = "addTime")
    @JoinColumn(name = "product_id")
    public List<EmployeePostCommission> postCommissions=new ArrayList<>();

    @ManyToMany
    @JoinTable(
            name = "product_of_spec",
            joinColumns = {@JoinColumn(name = "product_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "spec_id", referencedColumnName = "id")}
    )
    private Set<ProductSpec> productSpecs=new HashSet<>();

    private boolean capture;

    /**
     * 修改时段
     *
     * @param productSupplyTime
     */
    public void updateSupplyTimes(ProductSupplyTime productSupplyTime) {
        if (supplyTimes.indexOf(productSupplyTime.getId()) != -1) {
            JSONArray jsonArray = new JSONArray(supplyTimes);
            int subscript = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String supplyTimeId = jsonObject.getString("id");
                if (StringUtils.equals(id, supplyTimeId)) {
                    subscript = i;
                    break;
                }
            }
            jsonArray.remove(subscript);
            JSONObject jsonObject = new JSONObject(productSupplyTime);
            jsonArray.put(jsonObject);
            supplyTimes = jsonArray.toString();
        }

    }


    /**
     * 删除时段
     *
     * @param id
     */
    public void deleteSupplyTimes(String id) {
        if (supplyTimes.indexOf(id) != -1) {
            JSONArray jsonArray = new JSONArray(supplyTimes);
            int subscript = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String supplyTimeId = jsonObject.getString("id");
                if (StringUtils.equals(id, supplyTimeId)) {
                    subscript = i;
                    break;
                }
            }
            jsonArray.remove(subscript);
            supplyTimes = jsonArray.toString();
        }

    }


    /**
     * 获取时段提示
     *
     * @return
     */
    public String getMsg() {
        StringBuffer stringBuffer = new StringBuffer();
        if (supplyTimes != null && supplyTimes.indexOf("beginHour") != -1) {
            JSONArray jsonArray = new JSONArray(supplyTimes);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int beginHour = jsonObject.getInt("beginHour");
                int endHour = jsonObject.getInt("endHour");
                int beginMinute = jsonObject.getInt("beginMinute");
                int endMinute = jsonObject.getInt("endMinute");
                if (i == 0) {
                    stringBuffer.append("添加失败！该商品供应时间段为：");
                }
                stringBuffer.append(beginHour);
                stringBuffer.append(":");
                stringBuffer.append(beginMinute);
                stringBuffer.append("--");
                stringBuffer.append(endHour);
                stringBuffer.append(":");
                stringBuffer.append(endMinute);
                if (i != jsonArray.length() - 1) {
                    stringBuffer.append(",");
                }
            }
        }
        return stringBuffer.toString();
    }


    public double returnGroupComission(String groupId){
        for (EmployeePostCommission postCommission : this.postCommissions) {
            if (postCommission.getGroupId().equals(groupId)){
                return postCommission.getCommission();
            }
        }
        return 0;
    }


    /**
     * 判断商品供应时间段
     *
     * @return
     */
    public boolean checkSupplyTime() {
        ZoneId america = ZoneId.of("Asia/Shanghai");
        ZonedDateTime zonedDateTime = ZonedDateTime.now(america);
        int hour = zonedDateTime.getHour();
        int minute = zonedDateTime.getMinute();
        boolean status = false;
        if (supplyTimes != null && supplyTimes.indexOf("beginHour") != -1) {
            JSONArray jsonArray = new JSONArray(supplyTimes);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int beginHour = jsonObject.getInt("beginHour");
                int endHour = jsonObject.getInt("endHour");
                int beginMinute = jsonObject.getInt("beginMinute");
                int endMinute = jsonObject.getInt("endMinute");
                if (hour < beginHour || hour > endHour) {
                    continue;
                }

                if (endHour == hour && hour == beginHour &&
                        minute >= beginMinute && minute <= endMinute) {
                    status = true;
                    break;
                } else if ((beginHour < hour && hour < endHour) ||
                        (beginHour == hour && hour < endHour && minute >= beginMinute) ||
                        (beginHour < hour && hour == endHour && minute <= endMinute)) {
                    status = true;
                    break;
                }
            }
        } else {
            status = true;
        }

        return status;
    }


    public String checkProduct(boolean isStockLimitSales, int qty) {
        String msg = null;
        if (productStatus == ProductStatus.OFF) {
            msg = "添加失败！商品已下架！";
        } else if (stockEnabled && isStockLimitSales && quantity - qty < 0) {
            msg = "添加失败！商品库存不足！";
        }
        return msg;
    }


}
